#include "pch.h"
#include "include/linelink.h"
#include "include/protocol.h"

LineLink::LineLink()
{

}
LineLink::~LineLink()
{

}
//-------------------------------------------------------------------------------------
void LineLink::OnClose(UINT32 dwConnID, int err)
{
	for (auto it = m_oMapLine2Conn.begin(); it!=m_oMapLine2Conn.end(); it++)
	{
		if (it->second == dwConnID)
		{
			UINT32 dwLine = it->first;
			m_oMapLine2Conn.erase(it);
			this->OnLineClosed(dwLine);
			return;
		}
	}
}

//Line
bool LineLink::SendToLine(UINT32 dwLine, const CProtocol& roPtc)
{
	CMapLine2Conn::iterator it = m_oMapLine2Conn.find(dwLine);
	if (it == m_oMapLine2Conn.end())
	{
		LogError("LineLink::SendToLine line:%d, not found!!!!, roPtc.dwType:%u", dwLine, roPtc.m_dwType);
		return false;
	}
	return CNetProcessor::Instance()->Send(it->second, roPtc);
}

bool LineLink::SendToLine(UINT32 dwLine, const CRpc& roRpc)
{
	CMapLine2Conn::iterator it = m_oMapLine2Conn.find(dwLine);
	if (it == m_oMapLine2Conn.end())
	{
		LogError("LineLink::SendToLine line:%d, not found!!!!", dwLine);
		return false;
	}
	return CNetProcessor::Instance()->Send(it->second, const_cast<CRpc &>(roRpc));
}


bool LineLink::SendToAllLine(const CProtocol& roPtc)
{
	for (auto it = m_oMapLine2Conn.begin(); it != m_oMapLine2Conn.end(); it++)
	{
		CNetProcessor::Instance()->Send(it->second, roPtc);
	}
	return true;
}

bool LineLink::SendToAllLine(const CRpc& roRpc)
{
// 	for (auto it = m_oMapLine2Conn.begin(); it != m_oMapLine2Conn.end(); it++)
// 	{
// 		CNetProcessor::Instance()->Send(it->second, roRpc);
// 	}
	return false;
}


bool LineLink::RegisterLine(UINT32 dwLine, UINT32 dwConnID)
{
	CMapLine2Conn::iterator it = m_oMapLine2Conn.find(dwLine);
	if (it != m_oMapLine2Conn.end())
	{
		LogError("LineLink::RegisterLine line:%d, allready exist!!!!", dwLine);
		return false;
	}
	LogInfo("LineLink::RegisterLine line:%d, dwConnID:%d", dwLine, dwConnID);
	m_oMapLine2Conn[dwLine] = dwConnID;

	this->OnLineConnected(dwLine);
	return true;
}

bool LineLink::IsLineConnected(UINT32 dwLine) const
{
	return m_oMapLine2Conn.find(dwLine) != m_oMapLine2Conn.end();
}

UINT32 LineLink::GetConnID(UINT32 dwLine)
{
	CMapLine2Conn::iterator it = m_oMapLine2Conn.find(dwLine);
	if (it != m_oMapLine2Conn.end())
	{
		return it->second;
	}
	LogError("[%s] LineLink::GetConnID get line:%u not found!!!!", this->GetName().c_str(), dwLine);
	return 0;
}


